<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/4/18
 * Time: 12:42
 */

namespace app\admin\controller\statistics;
use app\admin\model\User;
use app\admin\model\wallet\Record;
use app\common\controller\Backend;

class Agent extends Backend
{
    /**
     * 查询统计
     * 总投注，总上分，总提款，总赠送
     */
    public function index()
    {
        $date = $this->request->post();


        $data = $this->getOrderStatisticsData($date);
        $statistics = ['columns' => array_keys($data['list']), 'data' => array_values($data['list']),'statistics'=>$data['statistics']];
        if ($this->request->isPost()) {
            $this->success('', '', $statistics);
        }

        $statistics['totalbets']    = number_format(Record::where('type',3)->where('pay_status',1)->sum('money'),2);//下注
        $statistics['totalupscore'] = number_format(Record::where('type',1)->where('pay_status',1)->sum('money'),2);//上分
        $statistics['totalwithdraw']= number_format(Record::where('type',2)->where('pay_status',1)->sum('money'),2);//提现
        $statistics['totalgive']    = number_format(10000,2);//赠送

        $statistics['todaybets']   = number_format(Record::where('type',3)->where('pay_status',1)->whereTime('createtime', 'today')->sum('money'),2);//今日下注
        $statistics['todayupscore']= number_format(Record::where('type',1)->where('pay_status',1)->whereTime('createtime', 'today')->sum('money'),2);//今日上分
        $statistics['todaywithdraw']= number_format(Record::where('type',2)->where('pay_status',1)->whereTime('createtime', 'today')->sum('money'),2);//今日提现
        $statistics['totaygive']   = number_format(5000,2);//赠送
        $this->view->assign('statistics', $statistics);
        $this->assignconfig('statistics', $statistics);
        return $this->view->fetch();
    }

    /**
     * 获取订单统计数据
     * @param string $date
     * @return array
     */
    protected function getOrderStatisticsData($data = '')
    {
        $statistics = ['upscore'=>0.00,'withdraw'=>0.00,'bets'=>0.00,'give'=>0.00,'profit'=>0.00];
        $date = isset($data['date']) ? $data['date'] : '';
        if( isset($data['account']) && $data['account'] ){
            $user = User::where('username','=',$data['account'])->field('id,group_id')->find();
            if( $user['group_id'] == 3 ){ //group_id = 3 查询代理团队的报表
                $user_ids = User::where('pid','=',$user['id'])->where('group_id',2)->column('id');
                //$user_ids = array_merge($user_ids,[$user['id']]);
            }
        }else{
            return ['list'=>[],'statistics'=>$statistics];
        }
        if ($date) {
            list($start, $end) = explode(' - ', $date);

            $starttime = strtotime($start);
            $endtime = strtotime($end);
        } else {
            $starttime = \fast\Date::unixtime('day', 0, 'begin');
            $endtime = \fast\Date::unixtime('day', 0, 'end');
        }
        $totalseconds = $endtime - $starttime;

        $format = '%Y-%m-%d';
        if ($totalseconds > 86400 * 30 * 2) {
            $format = '%Y-%m';
        } else if ($totalseconds > 86400) {
            $format = '%Y-%m-%d';
        } else {
            $format = '%H:00';
        }
        $betslist = Record::where('createtime', 'between time', [$starttime, $endtime])->where('type',3)
            ->whereIn('user_id',$user_ids)
            ->where('pay_status',1)
            ->field('pay_status,createtime, money, SUM(money) AS nums, MIN(createtime) AS min_createtime, MAX(createtime) AS max_createtime,
            DATE_FORMAT(FROM_UNIXTIME(createtime), "' . $format . '") AS bets_date')
            ->group('bets_date')
            ->select();//投注


        $lists = Record::where('createtime', 'between time', [$starttime, $endtime])
            ->whereIn('user_id',$user_ids)
            ->where('pay_status',1)
            ->field('SUM(money) as nums,type,pay_status')
            ->group('type')
            ->select();//投注
        $zhongjiang = 0;
        $xiazhu = 0;
        $upscore = 0;
        $downscore = 0;
        foreach ( $lists as $list ){
            if( $list['type'] == 1 || $list['type'] == 7 || $list['type'] == 8 ){
                $upscore +=$list['nums'];
                //$statistics['upscore'] = substr(sprintf("%.3f",$upscore),0,-1);
            }
            if( $list['type'] == 2 ){
                $statistics['withdraw'] = substr(sprintf("%.3f",$list['nums']),0,-1);
            }
            if( $list['type'] == 3 ){
                $statistics['bets'] = $list['nums'];
                $xiazhu = $xiazhu + $list['nums'];
            }
            if( $list['type'] == 5 ){
                $statistics['give'] = substr(sprintf("%.3f",$list['nums']),0,-1);
            }
            if( $list['type'] == 4 ){
                $zhongjiang += $zhongjiang + $list['nums'];
            }
            if( $list['type'] == 9 ){
                $downscore += $downscore + $list['nums'];
            }
        }
        $statistics['profit'] = substr(sprintf("%.3f",$xiazhu-$zhongjiang+$downscore),0,-1);
        $statistics['upscore'] = substr(sprintf("%.3f",$upscore-$downscore),0,-1);
        if ($totalseconds > 84600 * 30 * 2) {
            $starttime = strtotime('last month', $starttime);
            while (($starttime = strtotime('next month', $starttime)) <= $endtime) {
                $column[] = date('Y-m', $starttime);
            }
        } else if ($totalseconds > 86400) {
            for ($time = $starttime; $time <= $endtime;) {
                $column[] = date("Y-m-d", $time);
                $time += 86400;
            }
        } else {
            for ($time = $starttime; $time <= $endtime;) {
                $column[] = date("H:00", $time);
                $time += 3600;
            }
        }
        $list = array_fill_keys($column, 0);
        foreach ($betslist as $k => $v) {
            $list[$v['bets_date']] = $v['nums'];
        }
        return ['list'=>$list,'statistics'=>$statistics];
    }
}